'use strict';
const Controller = require('egg').Controller;
const images = require("images")
// const moment = require('moment');


class Dfs extends Controller {
  /**
   * 展示所有桶
   */
  async listBuckets() {
    const { app, ctx } = this
    let data = await ctx.service.dfs.listBuckets()
    ctx.body = data
  }
  /**
  * 判断桶是否存在
  */
  async bucketExists() {
    const { app, ctx } = this
    let { name } = ctx.query
    let data = await ctx.service.dfs.bucketExists(name)
    console.log(12222, data)
    ctx.body = data
  }

  /**
  * 上传单个文件（http）
  */
  async putObject() {
    const { app, ctx } = this
    let data = await ctx.service.dfs.putObject()
    ctx.body = data
  }
  /**
  * 上传单个文件（本地文件）
  */
  async fPutObject() {
    const { app, ctx } = this
    let data = await ctx.service.dfs.fPutObject()
    ctx.body = data
  }
  /**
  * 复制文件
  * 有错误，不支持该接口
  */
  async copyObject() {
    const { app, ctx } = this
    let data = await ctx.service.dfs.copyObject()
    ctx.body = data
  }
  /**
  * 删除桶单个文件
  */
  async removeObject() {
    const { app, ctx } = this
    let data = await ctx.service.dfs.removeObject()
    ctx.body = data
  }
  /**
  * 展示桶内所有文件
  */
  async listObjects() {
    const { app, ctx } = this
    let data = await ctx.service.dfs.listObjects()
    ctx.body = data
  }
  /**
   * 预览/下载文件
   */
  async getObject() {
    const { app, ctx } = this
    let { download, w, h } = ctx.query
    let { fileName, data, fileType, hz } = await ctx.service.dfs.getObject()
    function isAssetTypeAnImage(ext) {
      return ['png', 'jpg', 'jpeg', 'bmp', 'webp', 'svg', 'tiff'].includes(ext);
    }
    
    let newImage
    if (isAssetTypeAnImage(hz)) {
      if (w||h) {
        newImage = await images(data).resize(Number(w), Number(h)).encode('jpg', { operation: 90 });
      }
      else newImage = data

      if (download || download == '') {
        ctx.set('Content-Type', 'application/octet-stream');
        ctx.set('Content-Disposition', `attachment;filename=${fileName}`);
      } else {
        ctx.set('Content-Type', fileType);
      }
    }
    else {
      newImage = data
      ctx.set('Content-Type', 'application/octet-stream');
      ctx.set('Content-Disposition', `attachment;filename=${fileName}`);
    }

    ctx.body = newImage
  }

  async getPresinedUrl() {
    const { app, ctx } = this
    let data = await ctx.service.dfs.getPresinedUrl()
    ctx.body = data
  }

}
module.exports = Dfs